import type { SysUser } from "@/entity/SysUser";
import { BaseEntityService } from "./base-entity.service";
import httpClient from "./http-client";
import type { AxiosResponse } from "axios";
import { ResetPasswordParam } from "@/entity/ResetPasswordParam";

export class SysUserService extends BaseEntityService<SysUser> {
    baseUrl = "/api/v1.0/admin/user";

    async resetPassword(id: number, newPassword?: string) {
        const param = new ResetPasswordParam();
        param.id = id;
        param.password = newPassword;
        return httpClient.post(`${this.baseUrl}/reset-password`, param);
    }

    async uploadAvatar(id: number, file: File) {
        const formData = new FormData();
        formData.append("file", file);
        return httpClient.post(`${this.baseUrl}/update-avatar/${id}`, formData, true, {
            headers: {
                "Content-Type": "multipart/form-data;charset=utf-8",
            }
        });
    }

    async removeAvatar(id: number) {
        return httpClient.delete(`${this.baseUrl}/remove-avatar/${id}`);
    }

    async exportData() {
        return httpClient.post(`${this.baseUrl}/export`, undefined, undefined, {
            headers: {},
            responseType: "blob",
        }).then((res: AxiosResponse<any>) => {
            console.log(res);
            let blob = res.data;
            let fileName = new Date().getTime() + '.xlsx';

            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.click();
            //释放内存
            window.URL.revokeObjectURL(link.href);

            return Promise.resolve(res.data);
        });
    }

    async importData(file: File) {
        const formData = new FormData();
        formData.append("file", file);
        return httpClient.post(`${this.baseUrl}/import`, formData, true, {
            headers: {
                "Content-Type": "multipart/form-data;charset=utf-8",
            }
        });
    }
}

const userService = new SysUserService();

export default userService;